package com.quectel.core.module.propertybill.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.household.HouseholdConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.household.dto.HouseholdRoomDto;
import com.quectel.core.module.household.service.HouseholdRoomService;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.propertybill.dao.PropertyBillActivityDao;
import com.quectel.core.module.propertybill.dto.PropertyBillActivityDto;
import com.quectel.core.module.propertybill.dto.PropertyBillDto;
import com.quectel.core.module.propertybill.entity.PropertyBillActivityEntity;
import com.quectel.core.module.propertybill.service.PropertyBillActivityService;
import com.quectel.core.module.propertybill.service.PropertyBillService;
import com.quectel.core.module.village.service.VillageRoomService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/03/31 16:28
 */
@DubboService
public class PropertyBillActivityServiceImpl implements PropertyBillActivityService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertyBillActivityService.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PROPERTY_BILL_ACTIVITY_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PROPERTY_BILL_ACTIVITY_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PropertyBillActivityDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PROPERTY_BILL_ACTIVITY_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PropertyBillActivityDao propertyBillActivityDao;
    @Autowired
    private VillageRoomService villageRoomService;
    @Autowired
    private HouseholdService householdService;
    @Autowired
    private PropertyBillService propertyBillService;
    @Autowired
    private HouseholdRoomService householdRoomService;


    @Override
    public List<PropertyBillActivityDto> selectByBillId(Long billId) {
        //根据订单Id查询赠品列表
        List<PropertyBillActivityEntity> entities = propertyBillActivityDao.selectList(new LambdaQueryWrapper<PropertyBillActivityEntity>()
                .eq(PropertyBillActivityEntity::getBillId, billId));
        List<PropertyBillActivityDto> result = CopyUtils.copyList(entities, PropertyBillActivityDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public PropertyBillActivityDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PROPERTY_BILL_ACTIVITY_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PropertyBillActivityDto selectById(Long id) {
        PropertyBillActivityEntity entity = propertyBillActivityDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, PropertyBillActivityDto.class));
    }

    @Override
    public List<PropertyBillActivityDto> queryList(Map<String, Object> params) {
        List<PropertyBillActivityEntity> list = propertyBillActivityDao.queryList(params);
        List<PropertyBillActivityDto> result = CopyUtils.copyList(list, PropertyBillActivityDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PropertyBillActivityDto paddingField(PropertyBillActivityDto dto) {
        if (dto != null) {

            dto.setVillageRoom(villageRoomService.selectCacheById(dto.getRoomId()));

            List<HouseholdRoomDto> householdRoomDtos = householdRoomService.selectByRoomIdAndIdentityTypes(dto.getRoomId(), Collections.singletonList(HouseholdConstants.IDENTITY_CATEGORY_OWNER));
            if (CollectionUtils.isNotEmpty(householdRoomDtos)) {
                dto.setOwner(householdRoomDtos.get(0).getHouseholdDto());
            }

            PropertyBillDto propertyBillDto = propertyBillService.selectCacheById(dto.getBillId());
            dto.setPropertyBill(propertyBillDto);
        }

        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return propertyBillActivityDao.queryTotal(params);
    }

    @Override
    public Long save(PropertyBillActivityDto dto) {
        PropertyBillActivityEntity entity = CopyUtils.copyObj(dto, PropertyBillActivityEntity.class);
        entity.setId(Snowflake.nextId());
        propertyBillActivityDao.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateById(PropertyBillActivityDto dto) {
        PropertyBillActivityEntity entity = CopyUtils.copyObj(dto, PropertyBillActivityEntity.class);

        propertyBillActivityDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(PropertyBillActivityDto dto) {
        PropertyBillActivityEntity entity = CopyUtils.copyObj(dto, PropertyBillActivityEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, propertyBillActivityDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        propertyBillActivityDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
